package com.fsy.Controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fsy.entities.*;
import com.fsy.mapper.StudentsMapper;
import com.fsy.mapper.UsersMapper;
import com.fsy.service.*;
import com.fsy.utils.ExcelUtil;
import com.fsy.utils.ObjectConversion;
import com.fsy.utils.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/students")
public class StudentsController {
    @Resource
    private StudentsService studentsService;
    @Resource
    private StudentsMapper studentsMapper;
    @Resource
    private UserrolesService userrolesService;
    @Resource
    private AskersService askersService;
    @Resource
    private MessageService messageService;
    @Resource
    private NetfollowsService netfollowsService;
    @Resource
    private UsersMapper usersMapper;

    /**
     *根据条件查询学生
     * @param students
     * @return
     */
    @GetMapping("/findByStudents")
        public Map<String,Object> findByStudents(Students students){
       /* QueryWrapper<Students> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("netpusherId",netpusherId);
        Students students1 = studentsService.getOne(queryWrapper);
        if (students == )*/
        //查询登录的用户都有什么角色
        List<Userroles> userroles = userrolesService.selectUserrolesById(students.getUserId());
        for (Userroles u : userroles) {
            if (u.getName().equals("咨询经理")) {
                students.setNetpusherId(null);
                break;
            } else {
                students.setNetpusherId(students.getUserId());
            }
        }
        //查询全部用户信息
        List<Students> studentsList = studentsService.selectAllByNetpusherIdAndIsValid(students);
        //查询全部用户数量
        int count = studentsService.selectCounts(students);
        return Result.toClient("0", "成功",count,studentsList);
    }

    @GetMapping("selectStudents")
    public Map<String,Object> selectStudents(Students students,Integer userId,Integer page,Integer limit){

        //获取当前登录用户的角色
        boolean isZXY = false; //是否是咨询员
        boolean isZXYL = false;//是否是咨询经理
        boolean isAll = false;//是否都是
        List<Roles> rolesList = studentsService.getRolesByUserId(userId);
        for (Roles r : rolesList){
            if ("咨询经理".equals(r.getName())){
                isZXYL = true;
            }
            if ("网络咨询员".equals(r.getName())){
                isZXY = true;
            }
        }
        if (isZXY && isZXYL){
            isAll = true;
        }

        QueryWrapper<Students> q1 = new QueryWrapper<>();
        q1.eq("isValid","1");
        if (isZXY && !isAll){
            q1.eq("netpusherId",userId).eq("isValid","1");
        }
        //查询条件
       /* q1.like(StringUtils.isBlank(students.getName()) ? false : true,
                        "name",students.getName())
                .ge(StringUtils.isBlank(students.getBegintime()) ? false : true,
                        "createTime",students.getCreateTime())
                .le(StringUtils.isBlank(students.getEndtime()) ? false : true,
                        "createTime",students.getCreateTime())
                .eq(StringUtils.isBlank(students.getStuStatus()) ? false : true,
                        "stuStatus",students.getStuStatus()) ;*/
        IPage<Map<String,Object>> rsl = studentsService.pageMaps(new Page<>(page,limit),q1);
        Map<String,Object>  rslmap = new HashMap<>();
        rslmap.put("code","0");
        rslmap.put("msg","成功");
        rslmap.put("data",rsl.getRecords());//取数据
        rslmap.put("count",rsl.getTotal());//取总条数
        return rslmap;

    }

    /**
     * 导出excel表
     * @param response
     * @param students
     */
    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response, Students students){
        //查询登录的用户都有什么角色
        List<Userroles> userroles = userrolesService.selectUserrolesById(students.getUserId());
        for (Userroles u : userroles) {
            if (u.getName().equals("咨询经理")) {
                students.setNetpusherId(null);
                break;
            } else {
                students.setNetpusherId(students.getUserId());
            }
        }
        //查询数据
        List<Students_exportExcel> list = studentsService.exportMember(students);
        //导出到excel里
        ExcelUtil.export(response,"students","students",list,Students_exportExcel.class);
    }

    /**
     * 导出excel
     *我的学生
     * @param response
     * @param students
     */
    @GetMapping("/exportMyStudent")
    public void exportMyStudent(HttpServletResponse response, Students students) {
        //查询登录的用户都有什么角色
        List<Userroles> userroles = userrolesService.selectUserrolesById(students.getUserId());
        for (Userroles u : userroles) {
            if (u.getName().equals("咨询经理")) {
                students.setAskerId(null);
                break;
            } else {
                students.setAskerId(students.getUserId());
            }
        }
        List<Students_exportExcel> list = studentsService.exportMyStudents(students);
        ExcelUtil.export(response, "students", "students", list, Students_exportExcel.class);
    }
    /**
     * 导入excel表
     * @param file
     * @return
     */
    @PostMapping("/importExcel")
    public Map<String, Object> importExcel(MultipartFile file,Students students) {
        Users users = usersMapper.selectById(students.getNetpusherId());
        students.setNetpusherId(students.getNetpusherId());
        students.setCreateUser(users.getLoginName());
        List<Students_importExcel> importList = ExcelUtil.importExcel(file, Students_importExcel.class, null);
        //把importList集合复制到另外一个集合（存的是member对象）
        List<Students> memberList = ObjectConversion.copy(importList, Students.class);
        for (Students s:memberList){
            s.setNetpusherId(students.getNetpusherId());
            s.setCreateUser(users.getLoginName());
        }
        System.out.println(memberList);
        Boolean rel = studentsService.saveBatch(memberList);//执行保存
        Map<String, Object> rslmap = new HashMap<>();
        rslmap.put("code", rel ? "0" : "1");
        rslmap.put("msg", rel ? "导入成功" : "导入失败");
        return rslmap;
    }

    /**
     * 添加学生
     * @param students
     * @return
     */
    @PostMapping("/insertStudents")
    public Map<String,Object> insertStudents(Students  students){
        Users users = usersMapper.selectById(students.getNetpusherId());
        students.setCreateUser(users.getLoginName());
        List<Students> list = studentsService.list();
        for (int i=0;i<list.size();i++){
            if(students.getName().equals(list.get(i).getName())){
                return Result.toClient("1", "已有此学生姓名");
            }
        }
        Boolean rel = studentsService.save(students);
        Map<String ,Object> rslmap =new HashMap<>();
        if (rel){
            rslmap.put("code","0");
            rslmap.put("msg","添加成功");
        }else{
            rslmap.put("code","1");
            rslmap.put("msg","添加失败");
        }
        return rslmap;
    }

    /**
     * 删除
     */
    @DeleteMapping("/{id}")
    public Map<String, Object> deleteById(@PathVariable Integer id){
        boolean rel = studentsService.removeById(id);
        return rel == true ? Result.toClient("0", "删除成功") : Result.toClient("1", "删除失败");
    }


    //获取咨询师
    @GetMapping("/findAllAskers")
    public List<Askers> findAllAskers(){
        return askersService.list();
    }

    /**
     * 分配咨询师
     * @param studentIds
     * @param askerId
     * @param askerName
     * @return
     */
    @PostMapping("/batchFenZXS")
    public Map<String,Object> batchFenZXS(@RequestParam("studentIds") List<Integer> studentIds,String askerId,String askerName){
        //update students set stustatus = 2,askerId =xx,zixunname = xxx where id in(1,2,2)
        UpdateWrapper<Students> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("stuStatus","2").set("askerId",askerId).set("ziXunName",askerName).in("id",studentIds);
        return studentsService.update(updateWrapper) ? Result.toClient("0","分配成功") : Result.toClient("0","分配失败");
    }

    /**
     * 发消息
     * @param message
     * @return
     */
    @PostMapping("/sendmessage")
    public Map<String,Object> updateStu(Message message){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dqsj = df.format(new Date());
        Students students = studentsMapper.selectById(message.getId());
        Message m = new Message();
        m.setContent(message.getContent());
        m.setSenderId(message.getSenderId());
        m.setSenderName(message.getSenderName());
        m.setReceiverId(students.getAskerId());
        m.setReceiverName(students.getZiXunName());
        m.setSendTime(dqsj);
        m.setIsRead(2);
        boolean rs1=messageService.save(m);
        Map<String,Object> map=new HashMap<>();
        if (rs1){
            map.put("code","0");
            map.put("msg","成功");
        }else {
            map.put("code","1");
            map.put("msg","修改失败");
        }
        return map;
    }

    /**
     * 查询全部
     * 我的学生
     * @param students
     * @return
     */
    @GetMapping("/selectAllMyStudent")
    public Map<String,Object> selectAllMyStudent(Students students){
        //查询登录的用户都有什么角色
        List<Userroles> userroles = userrolesService.selectUserrolesById(students.getUserId());
        for (Userroles u : userroles) {
            if (u.getName().equals("咨询经理")) {
                students.setAskerId(null);
                break;
            } else {
                students.setAskerId(students.getUserId());
            }
        }
        List<Students> studentsList = studentsService.selectAllByIsValidAndAskerId(students);
        int count = studentsService.selectStudentCount(students);
        return Result.toClient("0", "成功", count, studentsList);
    }

    /**
     * 修改我的学生信息
     * @param students
     * @return
     */
    @PostMapping("/updateStudent")
    public Map<String,Object> updateStudent(Students students){
        boolean rsl = studentsService.updateById(students);
        return rsl == true?Result.toClient("0","修改成功"):Result.toClient("1","修改失败");
    }

    /**
     * 添加跟踪信息
     */
    @PostMapping ("/AddStuNet")
    public Map<String, Object> AddStuNet(Netfollows netfollows) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("studentId",netfollows.getStudentId());
        long count = netfollowsService.count(wrapper);
        Students students =new Students();
        UpdateWrapper<Students> wrapper1 = new UpdateWrapper();
        if (netfollows.getFollowState()==1){
            wrapper1.set("stuStatus",4).eq("id",netfollows.getStudentId());
        }else if (netfollows.getFollowState()==2){
            wrapper1.set("stuStatus",3).eq("id",netfollows.getStudentId());
        }else {
            wrapper1.set("stuStatus",5).eq("id",netfollows.getStudentId());
        }
        studentsService.update(wrapper1);
        if (count == 0){
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dqsj = df.format(new Date());
            UpdateWrapper<Students> updateWrapper = new UpdateWrapper();
            updateWrapper.set("firstVisitTime",dqsj).eq("id",netfollows.getStudentId());
            studentsService.update(updateWrapper);
        }
        boolean save = netfollowsService.save(netfollows);
        if (save == true){
            return Result.toClient("0","添加成功");
        }else {
            return Result.toClient("0","添加失败");
        }
    }

    //统计各个咨询师负责的学生人数
    @GetMapping("askerStudentCountReport")
    public List<Report> askerStudentCountReport(){
        return studentsService.askerStudentCountReport();
    }

    // 统计各个网络咨询员录入的学生人数
    @GetMapping("wlzxyStudentCountReport")
    public List<Report>wlzxyStudentCountReport(){
        return studentsService.wlzxyStudentCountReport();
    }

}
